// 验证注册码，并更新App试用期
const crypto = require('crypto')
const fs = require('fs')
const path = require('path')
const dataFilePath = path.join(__dirname, 'used_registration_codes.json')
const configFilePath = path.join(__dirname, 'configs.json')
// AES 解密
function decrypt(encryptedText, secretKey) {
  const [ivHex, encrypted] = encryptedText.split(':')
  const iv = Buffer.from(ivHex, 'hex')
  const decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(secretKey), iv)
  let decrypted = decipher.update(encrypted, 'hex', 'utf8')
  decrypted += decipher.final('utf8')
  return decrypted
}
function verifyRegCode(regcode) {
  const secretKey = 'yilongchen1yilongchen2yilongchen' //用于HMAC的密钥
  const [payloadaes, hash] = regcode.split('--')
  const payload = decrypt(payloadaes, secretKey)
  const [userId, durationInDays, timestamp] = payload.split('*')

  // 重新生成HMAC并比较
  const expectHash = crypto.createHmac('sha256', secretKey).update(payload).digest('hex')
  if (hash !== expectHash) {
    return { valid: false, message: '无效的注册码' }
  }
  const now = Date.now()
  if (now - timestamp > 24 * 60 * 60 * 1000) {
    return { valid: false, message: '注册码已过期' }
  }
  // 检查注册码是否已被使用
  let usedCodes = []
  try {
    const data = fs.readFileSync(dataFilePath, 'utf8')
    usedCodes = JSON.parse(data)
  } catch (error) {
    console.error('无法读取文件:', error)
  }
  if (usedCodes.includes(regcode)) {
    return { valid: false, message: '注册码已被使用' }
  }
  // 更新已使用的注册码列表
  usedCodes.push(regcode)
  extendTrialPeriod(durationInDays)
  fs.writeFileSync(dataFilePath, JSON.stringify(usedCodes, null, 2), 'utf8')
  return { valid: true, userId, durationInDays }
}
// 更新使用期限
function extendTrialPeriod(durationInDays) {
  let app_configs = {}
  const now = new Date()
  try {
    const data = fs.readFileSync(configFilePath, 'utf8')
    app_configs = JSON.parse(data)
  } catch (error) {
    console.error('无法读取文件:', error)
  }
  const currentEndDateStr = app_configs['trialEndDate']
  let currentEndDate =
    currentEndDateStr && new Date(currentEndDateStr) > now ? new Date(currentEndDateStr) : now
  let newendDate = new Date(currentEndDate)
  console.log('到期日更改前', newendDate)
  newendDate.setDate(currentEndDate.getDate() + parseInt(durationInDays))
  console.log('到期日更改后', newendDate)
  // 将结束日期存储到json文件
  app_configs['trialEndDate'] = newendDate
  fs.writeFileSync(configFilePath, JSON.stringify(app_configs, null, 2), 'utf8')
}
let res = verifyRegCode(
  '2a952fae4501604dbcda3ed45aac0164:1862b3119ce41deb3d7dafe2397613cc319313183408d2df2b99867cd0c086f4--e6f60bcc70d37b93ebf71b2794d47a9d07305c4c1e712b1a8e2b0d27b1826323'
)
console.log(res)
